const bcryptjs = require('bcryptjs')
const { Sequelize, Model, DataTypes } = require('sequelize')
const { AuthFailed } = require('../../core/http-exception')

const { sequelize } = require('../../core/db')
const saltRounds = 10

class User extends Model {
  // 验证邮箱账号密码是否正确
  static async verifyEmailPassword(email, secret) {
    const user = await User.findOne({
      where: {
        email,
      },
    })

    if (!user) {
      throw new AuthFailed('用户不存在')
    }

    // 验证密码
    const correct = await bcryptjs.compareSync(secret, user.password)
    if (!correct) {
      throw new AuthFailed('账号或者密码不正确')
    }
    return user
  }
  static async verifyAccount({ field, account, secret }) {
    const user = await User.findOne({
      where: {
        [field]: account,
      },
    })

    if (!user) {
      throw new AuthFailed('用户不存在')
    }

    // 验证密码
    const correct = await bcryptjs.compareSync(secret, user.password)
    if (!correct) {
      throw new AuthFailed('账号或者密码不正确')
    }
    return user
  }
}

User.init(
  {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    nickname: DataTypes.STRING,
    account: {
      type: DataTypes.STRING(128),
      unique: true,
    },
    email: {
      type: DataTypes.STRING(128),
      unique: true,
    },
    password: {
      type: DataTypes.STRING,
      set(val) {
        const salt = bcryptjs.genSaltSync(saltRounds)
        const pwd = bcryptjs.hashSync(val, salt)
        this.setDataValue('password', pwd)
      },
    },
  },
  { sequelize, modelName: 'user' }
)

module.exports = User
